package uk.ac.ebi.bioinvindex.services;

import uk.ac.ebi.bioinvindex.dao.StudyDAO;
import uk.ac.ebi.bioinvindex.dao.ejb3.OntologyEntryDAOHelper;
import uk.ac.ebi.bioinvindex.model.impl.term.*;
import uk.ac.ebi.bioinvindex.model.impl.StudyImpl;
import uk.ac.ebi.bioinvindex.model.impl.MaterialImpl;
import uk.ac.ebi.bioinvindex.model.impl.processing.AssayImpl;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Nataliya Sklyar (nsklyar@ebi.ac.uk)
 * Date: Oct 8, 2007
 */
//@Name("studyBean")
public class StudyBeanImpl implements StudyBean{

	private StudyImpl study;

	private StudyDAO studyDao;

	private OntologyEntryDAOHelper ontologyEntryDAOHelper;

	private Map<AssayTechnology, List<AssayImpl>> assayTypeToAssay;

	public StudyBeanImpl(StudyImpl study) {
		this.study = study;
	}

	public List<MaterialImpl> getSourceMaterials() {
		MaterialRoleImpl roleSource = getOntologyEntryDAOHelper().getMaterialTypeByAcc(MaterialRoles.SOURCE.getAcc());
		return getStudyDao().getMaterialsOfType(this.study.getId(), roleSource);
	}


	public List<AssayTechnology> getAssayTypes() {
		return new ArrayList(getAssayByTypeMap().keySet());
	}


	public List<AssayImpl> getAssaysByType(AssayTechnology type) {
		return getAssayByTypeMap().get(type);
	}

	public StudyImpl getStudy() {
		return study;
	}

	public List<PropertyImpl> getFactors() {
		List factors = studyDao.getFactorsForStudy(study.getId());
		return factors;
	}

	public List<PropertyValueImpl> getOrganisms() {
		List<PropertyValueImpl> values = studyDao.getValuesOfProperty(study.getId(), "organism");
		return values;
	}

	private Map<AssayTechnology, List<AssayImpl>> getAssayByTypeMap() {
		if (assayTypeToAssay == null) {
			assayTypeToAssay = new HashMap<AssayTechnology, List<AssayImpl>>();

			for (AssayImpl assay : study.getAssays()) {
				if (!assayTypeToAssay.containsKey(assay.getTechnology())) {
					List<AssayImpl> list = new ArrayList<AssayImpl>();
					assayTypeToAssay.put(assay.getTechnology(), list);
				}

				List<AssayImpl> list = assayTypeToAssay.get(assay.getTechnology());
				list.add(assay);

			}
		}
		return assayTypeToAssay;
	}

	//////////////////////////
	// Dependencies injection

	public StudyDAO getStudyDao() {
		if (studyDao == null) {
			throw new IllegalStateException("StudyDAO is required but has not been set");
		}
		return studyDao;
	}

	public void setStudyDao(StudyDAO studyDao) {
		this.studyDao = studyDao;
	}

	public OntologyEntryDAOHelper getOntologyEntryDAOHelper() {
		if (ontologyEntryDAOHelper == null) {
			throw new IllegalStateException("OntologyEntryDAOHelper is required but has not been set");
		}
		return ontologyEntryDAOHelper;
	}

	public void setOntologyEntryDAOHelper(OntologyEntryDAOHelper ontologyEntryDAOHelper) {
		this.ontologyEntryDAOHelper = ontologyEntryDAOHelper;
	}


	public String toString() {
		return "StudyBeanImpl{" +
				"study=" + study +
				'}';
	}
}

